package com.japancompany.controller;

import com.japancompany.common.Result;
import com.japancompany.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
public class FileUploadController {

    @Autowired
    private FileService fileService;

    @Value("${file.upload.path:./uploads}")
    private String uploadPath;

    @Value("${file.access.url:/uploads}")
    private String accessUrl;

    @PostMapping("/image")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只支持图片文件");
            }

            // 验证文件大小 (5MB)
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.error("图片大小不能超过5MB");
            }

            // 创建上传目录
            String imageDir = uploadPath + "/images";
            File directory = new File(imageDir);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString() + extension;

            // 保存文件
            Path filePath = Paths.get(imageDir, newFilename);
            Files.copy(file.getInputStream(), filePath);

            // 保存文件记录到数据库
            String accessPath = accessUrl + "/images/" + newFilename;
            fileService.saveFile(originalFilename, accessPath, "image", file.getSize());

            return Result.success("上传成功", accessPath);

        } catch (IOException e) {
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }

    @PostMapping("/file")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 验证文件大小 (10MB)
            if (file.getSize() > 10 * 1024 * 1024) {
                return Result.error("文件大小不能超过10MB");
            }

            // 创建上传目录
            String fileDir = uploadPath + "/files";
            File directory = new File(fileDir);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString() + extension;

            // 保存文件
            Path filePath = Paths.get(fileDir, newFilename);
            Files.copy(file.getInputStream(), filePath);

            // 保存文件记录到数据库
            String accessPath = accessUrl + "/files/" + newFilename;
            fileService.saveFile(originalFilename, accessPath, "file", file.getSize());

            return Result.success("上传成功", accessPath);

        } catch (IOException e) {
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }

    @PostMapping("/multiple")
    public Result<List<String>> uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) {
        List<String> fileUrls = new ArrayList<>();
        
        for (MultipartFile file : files) {
            try {
                String contentType = file.getContentType();
                String result;
                
                if (contentType != null && contentType.startsWith("image/")) {
                    result = uploadImage(file).getData();
                } else {
                    result = uploadFile(file).getData();
                }
                
                if (result != null) {
                    fileUrls.add(result);
                }
            } catch (Exception e) {
                // 继续处理其他文件
                continue;
            }
        }
        
        return Result.success("上传成功", fileUrls);
    }

    @DeleteMapping("/file")
    public Result<String> deleteFile(@RequestParam String filePath) {
        try {
            // 从URL中提取文件名
            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            String fileType = filePath.contains("/images/") ? "images" : "files";
            
            Path filePathObj = Paths.get(uploadPath, fileType, fileName);
            Files.deleteIfExists(filePathObj);
            
            return Result.success("删除成功");
        } catch (IOException e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }
}